package com.cheng.spider.extract;

import com.cheng.spider.constant.ConstantMap;
import com.cheng.spider.constant.ConstantName;
import com.cheng.spider.constant.MimeType;
import com.cheng.spider.extract.novel.NovelExtractor;
import com.cheng.spider.util.CharsetNameUtil;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public abstract class TextDataResolver implements DataResolver {

    private static final Logger LOGGER = LoggerFactory.getLogger(TextDataResolver.class);

    protected SaveRule saveRule;

    public TextDataResolver() {
        this.saveRule = initSaveRule();
    }

    public void resolve(HttpResponse response, MimeType mimeType) {
        String text = convertResponseBody2Text(response, mimeType);
        Result result = parseText(text, mimeType);
        saveRule.save(result, mimeType);
    }

    private String getCharsetName(HttpResponse response) {
        //尝试从response中获取字符集编码，若无，使用默认编码
        String charsetName = CharsetNameUtil.getCharsetNameFromResponse(response);
        System.out.println("==============" + charsetName);
        return charsetName != null ? charsetName : ConstantMap.get(ConstantName.CHARSET_NAME);
    }

    private String convertResponseBody2Text(HttpResponse response, MimeType mimeType) {
        StringBuilder html = new StringBuilder(2048);
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), mimeType.getCharset()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                html.append(line);
            }
        } catch (IOException e) {
            LOGGER.error("将响应体转化为文本时发生错误");
            e.printStackTrace();
        }
        return html.toString();
    }

    protected abstract Result parseText(String text, MimeType mimeType);

    protected abstract SaveRule initSaveRule();
}
